<?php
/**
 * Created by PhpStorm.
 * User: 蒙明然
 * Date: 2017/9/5
 * Time: 9:34
 */

namespace app\operation\controller;


use app\common\model\Operation;
use app\common\model\WorkOrder;
use app\common\model\Engineers;
use app\common\model\Customer;
use think\session;
use think\db;

class Operations extends Base
{
    protected $Operation;
    protected $WorkOrder;
    protected $Engineer;
    protected $Customer;
    public function __construct()
    {
        parent::__construct();
        $this->WorkOrder=new WorkOrder();
        $this->Operation = new Operation();
        $this->Engineer=new Engineers();
        $this->Customer = new Customer();
    }

    /**
     * 行政中心显示
     * @return string|\think\response\Json
     */
    public function index(){
        /**
         * 根据运营中心ID查询对应的行政中心
         */
        //获取条件
        $request = input('');
        $where =array();
        $o_id=session($this->set['db_name'].'o_id');
        $where['rq_administrative_info.operation']=$o_id;//获取session中的运营中心ID
        foreach ($request as $k=>$v){
            if ($k == 'page'){
                continue;
            }
            if (empty($v)){
                continue;
            }
            if ($k == 'datetimeStart'){
                $where[$k] = $v;
                continue;
            }
            if ($k == 'datetimeEnd'){
                $where[$k] = $v;
                continue;
            }
            if ($k == 'area_id'){
                $where[$k] = ['like','%'.$v.'%'];
                continue;
            }
            if ($k == 'company_name'){
                $where['rq_administrative_info.'.$k] = ['like','%'.$v.'%'];
                continue;
            }
            if ($k == 'name'){
                $where['rq_administrative_info.'.$k] = ['like','%'.$v.'%'];
                continue;
            }
            if ($k == 'phone'){
                $where['rq_administrative_info.'.$k] = $v;
                continue;
            }
            $where[$k] = $v;
        }
        //获取页码
        $Nowpage = input('get.page') ? input('get.page'):1;
        //获取数据
        $lists = $this->Operation->selectDataProfile($Nowpage,$where);
        //更改时间格式
        foreach ($lists['data'] as $key=>$value){
            $lists['data'][$key]['add_time'] = date('Y-m-d H:i:s',$value['add_time']);
        }
        //获取管理员帐号
        foreach ($lists['data'] as $key=>$value){
            $aid=$this->Operation->bindAccount(4,['a_id'=>$lists['data'][$key]['a_id'],'is_admin'=>1,'is_delete'=>0]);
            $lists['data'][$key]['account']=$aid['account'];
            $op_id=$lists['data'][$key]['a_id'];
            $lists['data'][$key]['e_count']=count($this->Engineer->where(['administrative_id'=>$op_id])->select());
        }
//        dump($lists);exit;
        //模板输出
        $this->assign('Nowpage', $Nowpage); //当前页
        $this->assign('allpage', $lists['page']['allpage']); //总页数
        $this->assign('count', $lists['page']['count']);
        $json = array();
        $json['data'] = $lists['data'];
        $json['page'] =  $lists['page'];

        if(input('get.page')){
            return json($lists);
        }
        return $this->view->fetch();
    }
    /**
     * 行政中心详情
     */
    public function details(){
        $where = array();
        $id=input('get.id/d');
        $e_count=input('get.e_count');
        //检验get参数
        if (input('?get.id')){
            //获取参数并强制转换为int型
            $where['a_id'] =$id;
        }else{
            return json(array('code'=>0,'msg'=>'缺少必要参数'));
        }
        //获取数据
        $data = $this->Operation->findAdministrative($where);
        $aid=$this->Operation->bindAccount(4,['a_id'=>$id,'is_admin'=>1]);
        $center=$this->Operation->findOperation(['o_id'=>session($this->set['db_name'].'o_id')]);
        $data['account']=$aid['account'];
        $data['center']=$center['company_name'];
        $data['e_count']=$e_count;
        $data['add_time'] = date('Y-m-d H:i:s',$data['add_time']);
        //当前未完成工单数
        $map['work_order_status'] = [['>',0],['<',9],'and'];
        $map['administrative_id'] = $id;//当前行政区域ID
        $data['no_complete'] = $this->WorkOrder->getCount($map,'rq_work_order');
        //上月已完成工单数
        $map['work_order_status'] = 9;
        $map['administrative_id'] = $id;//当前行政区域ID
        $data['last_month'] = $this->WorkOrder->getCount($map,'rq_work_order','','','update_time','last month');
        $this->assign('data',$data);
        //渲染模板
        return $this->fetch("operations/details");
    }
    /**
     * 根据省获取市
     * @author 蒙明然
     * @Request province             int    GET   省ID
     * @return array
     */
    public function selectCity($province_id)
    {
        if($province_id){
        $City = $this->Operation->areasCity($province_id);
        return $City;}
        else{return false;}
    }
    //获取市重构方法
    public function Area()
    {
        $province_id = '';
        if(input('?get.province') && !empty(input('get.province'))) {
            $province_id = input('get.province/d');
        }if($province_id==2||$province_id==3||$province_id==10||$province_id==23){//判断是不是直辖市
            $temp = $this->selectCity($province_id);
            $p_id = $this->selectArea($temp[0]['id']);
        }
        else{
            $p_id = $this->selectCity($province_id);
        }
        return $p_id;
    }
    /**
     * 根据市获取区县
     * @author 蒙明然
     * @Request province             int    GET   省ID
     * @return array
     */
    public function selectArea($City_id)
    {
        if($City_id){
        $City = $this->Operation->areaName($City_id);
        return $City;}else{return false;}
    }
    /**
    * 添加（修改）行政区域---回显
    * @author  ligang
    * @request     int         o_id        GET     行政区域ID(修改)
    */
    public function editProfile()
    {
        //模板赋值
        if (input('?get.id')) {
            $id = input('get.id/d');
            $data = $this->Operation->findAdministrative(array('a_id' => $id));
            $area = array();
            if (strpos($data['area_name'], ',') != false) {
                $arr_area_name = explode(',', $data['area_name']);
                $arr_area_id = explode(',', $data['area_id']);
                foreach ($arr_area_name as $k => $v) {
                    $area[$k]['area_name'] = $v;
                    $area[$k]['area_id'] = $arr_area_id[$k];
                }
                $data['area'] = $area;
            }
            $checkAccount = $this->Operation->bindAccount(4,['a_id'=>$id,'is_admin'=>1]);
            if($checkAccount){
                $this->assign('admin',$checkAccount);
            }
//            dump($data);
            $this->assign('data', $data);
        }
        $o_id=session($this->set['db_name'].'o_id');
        $address = $this->Operation->selectOperationInfo(array('o_id'=>$o_id));//获取当前运营中心
        $province_id = $address[0]['province_id'];
        $Province = $this->Operation->areasProvince(array('id'=>$province_id));
        foreach ($Province as $key => $value){//获取对应管辖区域信息，排除直辖市
            if($Province[$key]['id']==2){
                $p_id=2;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==3){
                $p_id=3;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==10){
                $p_id=10;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==23){
                $p_id=23;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            $p_name=$address[0]['province_name'];
            $p_id=$Province[0]['id'];
            $p_data = $this->selectCity($p_id);
        }
        $operation = $this->Operation->selectOperationInfo();
        $administrative = $this->Operation->selectAdministrativeInfo();
        $this->assign('Area',$p_data);
        $this->assign('p_name',$p_name);
        $this->assign('p_id',$p_id);
        $this->assign('o_id',$o_id);
        $this->assign('operation',$operation);
        $this->assign('administrative',$administrative);

        //渲染模板
        return $this->view->fetch();
    }
    /**
     *  添加（修改）行政中心---回显
     * @author  ligang
     * @request     int         id        GET     页码
     */
    public function AddAdministrative(){
        $o_id=session($this->set['db_name'].'o_id');
        $address = $this->Operation->selectOperationInfo(array('o_id'=>$o_id));//获取当前运营中心
        $province_id = $address[0]['province_id'];
        //模板赋值
        $Province = $this->Operation->areasProvince(array('id'=>$province_id));
        foreach ($Province as $key => $value){//获取对应管辖区域信息，排除直辖市
            if($Province[$key]['id']==2){
                $p_id=2;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==3){
                $p_id=3;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==10){
                $p_id=10;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            if($Province[$key]['id']==23){
                $p_id=23;
                $p_name=$address[0]['province_name'];
                $City = $this->selectCity($p_id);
                $p_data=$this->selectArea($City[0]['id']);
                continue;
            }
            $p_name=$address[0]['province_name'];
            $p_id=$Province[0]['id'];
            $p_data = $this->selectCity($p_id);
        }
     //  dump($city);die();
        $this->assign('p_name',$p_name);
        $this->assign('p_id',$p_id);
        $this->assign('o_id',$o_id);
        $this->assign('Area',$p_data);
        //渲染模板
        return $this->fetch('operations/editprofile');
    }
    /**
     *  添加（修改）行政中心
     * @author  蒙明然
     */
    public function doEditOperation(){
        $data= $this->request->post();

        //去除空格
        foreach ($data as $tk=>$tv){
            if(!is_array($tv)){
                $data[$tk] = trim($tv);
            }
        }
        //分组
        $user = [];
        $admin = [];
        foreach ($data as $key => $value){
            if (strpos($key,'ser_') != false){
                $user[substr($key,5)] = $value;
                unset($data[$key]);
            }else{
                $admin[$key] = $value;
            }
        }
        $user['address'] = $admin['address'];
        $user['name'] = $admin['name'];
        $user['phone'] = $admin['phone'];
        //图片上传
        $file = request()->file('avatar_img');
        $is_upload = false;
        if(empty($file)){
            $is_upload = true;
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $user['avatar_img'] = $info->getSaveName();
            }
        }

        $area_id=$admin['area_id'];
        $area_name=$this->Operation->findAddrName($area_id);
        if(is_array($area_name)){
            $admin['area_name'] = '';
            foreach ($area_name as $k=>$v){
                $admin['area_name'].= $area_name[$k]['area_name'].',';
            }
            $admin['area_name'] = rtrim($admin['area_name'],',');
            $admin['area_id']=implode(',',$area_id);
        }else{
            $admin['area_name']=$area_name;
        }
        //判断是否为直辖市，直辖市 省=市 不为直辖市 则area=0
        if($admin['province_id']==2||$admin['province_id']==3||$admin['province_id']==10||$admin['province_id']==23){
            if($admin['province_id']==2){
                $admin['city_id']=36;
                $admin['city_name']=$admin['province_name'];
            }if($admin['province_id']==3){
                $admin['city_id']=37;
                $admin['city_name']=$admin['province_name'];
            }if($admin['province_id']==10){
                $admin['city_id']=108;
                $admin['city_name']=$admin['province_name'];
            }if($admin['province_id']==23){
                $admin['city_id']=271;
                $admin['city_name']=$admin['province_name'];
            }
        }
        else{
            $admin['city_id']=$admin['area_id'];
            $admin['city_name']=$admin['area_name'];
        }
        //验证


        if (strlen($admin['phone']) != 11){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：手机格式不正确";
            return json($json);
        }
        if (!inge_isemail($user['email'])){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：邮箱格式不正确";
            return json($json);
        }
        if (strlen($user['password']) <= 5 && !empty($user['password'])){
            $json['code'] = 0;
            $json['msg'] = "绑定账号：密码最少六位";
            return json($json);
        }
        if (empty($admin['company_name'])){
            $json['code'] = 0;
            $json['msg'] = "行政区域名称不能为空！";
            return json($json);
        }
        if (empty($admin['area_id'])){
            $json['code'] = 0;
            $json['msg'] = "负责区域不能为空！";
            return json($json);
        }
        if (empty($admin['address'])){
            $json['code'] = 0;
            $json['msg'] = "详细地址不能为空！";
            return json($json);
        }
        if (empty($admin['name'])){
            $json['code'] = 0;
            $json['msg'] = "联系人不能为空！";
            return json($json);
        }
        if (empty($admin['phone'])){
            $json['code'] = 0;
            $json['msg'] = "联系电话不能为空！";
            return json($json);
        }
        if(substr($admin['area_id'],'0',1)==','){
            $json['code'] = 0;
            $json['msg'] = "负责区域不正确！";
            return json($json);
        }
//        dump($admin);exit;
        //新增、修改操作
        if (!empty($admin['a_id'])){
            /**
             * 修改行政中心 + 绑定账号
             */
            if(!empty($user['password'])){
                $password = setPassword($user['password']);
                $user['password'] = $password['password'];
                $user['strict'] = $password['strict'];
            }else{
                unset($user['password']);
            }
            $user['is_delete']= 0;
            $admin['update_time'] = time();
            //更新操作
            Db::startTrans();
            try{
                //修改状态
                if ($admin['status'] == 0){
                    $FrozenAccount = $this->Operation->bindAccount(5,['a_id'=>$admin['a_id']],['status'=>0]);
                    if ($FrozenAccount){
                        //日志
                        writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】冻结成功：行政区域',1,'operation_log');
                    }else{
                        //日志
                        writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】冻结失败：行政区域',0,'operation_log');
                    }
                }else{
                    $FrozenAccount = $this->Operation->bindAccount(5,['a_id'=>$admin['a_id']],['status'=>1]);
                    if ($FrozenAccount){
                        //日志
                        writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】修改成功：行政区域',1,'operation_log');
                    }else{
                        //日志
                        writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】修改成功：行政区域',0,'operation_log');
                    }
                }
                $this->Operation->updateAdministrativen($admin);
                $this->Operation->updateAdministrativenAccount(['a_id'=>$admin['a_id'],'is_admin'=>1],$user);
                Db::commit();
                return json(array('code'=>1,'msg'=>'修改成功'));
            }catch (\Exception $e){
                echo $e;
                Db::rollback();
                return json(array('code'=>0,'msg'=>'修改失败'));
            }

        }else{
            /**
             * 新增运营中心 + 绑定账号
             */
            if ($is_upload){
                return json(['code'=>0,'msg'=>'请上传头像']);
            }

            $checkAdministrative = $this->Operation->findAdministrative(['company_name'=>$admin['company_name']]);
            if ($checkAdministrative){
                $json['code'] = 0;
                $json['msg'] = "行政中心名称已存在";
            }
            //检查绑定账号是否唯一
            $checkAccount = $this->Operation->bindAccount(4,['account'=>$user['account']]);
            if ($checkAccount){
                return  ['code'=>0,'msg'=>"账号已存在"];
            }
            if(empty($user['password'])){
                $user['password'] = 123456;
            }
            $password = setPassword($user['password']);
            $user['password'] = $password['password'];
            $user['strict'] = $password['strict'];
            $user['is_admin'] = 1;
            $user['add_time'] = time();
            $admin['add_time'] = time();
            unset($admin['a_id']);

//            dump($admin);exit;
            //更新操作
            Db::startTrans();
            try{
                $result = $this->Operation->insertAdministrativen($admin);
                $user['a_id'] = $result;
                $this->Operation->bindAccount(2,[],$user);
                Db::commit();
                return ['code'=>1,'msg'=>"新增成功"];
            }catch (\Exception $e){
                //echo $e;
                Db::rollback();
                return ['code'=>0,'msg'=>"新增失败"];
            }

        }
    }
    /**
     * 运营中心模块删除（行政中心）
     * 删除时，当前运营中心下面不能有下一级
     * @author  ligang
     * @request     array         id        GET     ID
     * @request     string        type      GET     模块
     */
    public function delete()
    {
        //定义返回格式
        $json = array('code'=>1,'msg'=>'提示信息');
        $data = input('');
        if (!empty($data['type']) && !empty($data['data'])) {
            $id = $data['data'];
            //行政区域
            foreach ($id as $key => $value) {
                //判断是否存在当前行政区域的账号
                $checkAccount = $this->Operation->bindAccount(4, ['a_id' => $value, 'is_delete' => 0]);
                //判断是否存在当前行政区域的工程人员
                $checkEngineers = $this->Operation->findEngineers(['administrative_id' => $value, 'is_delete' => 0]);
                if ($checkEngineers || $checkAccount) {
                    $json['code'] = 0;
                    $json['msg'] = "请删除所属行政区域账号和工程人员";
                    return json($json);
                    break;
                }
                $result = $this->Operation->deleteData('administrative_info', 'a_id', $value, '行政区域');
                if (!$result) {
                    $json['code'] = 0;
                    $json['msg'] = "删除失败";
                    break;
                } else {
                    $json['code'] = 1;
                    $json['msg'] = "删除成功";
                }
            }
            return json($json);
        }else{
            $json['code']=0;
            $json['msg']="缺少必要参数";
            return json($json);
        }
    }

    /**
     * 根据运营中心获取行政中心
     * @author ligang
     * @Request operation_id             int    GET   运营中心ID
     * @return array
     */
    public function selectAdministrative()
    {
        $where = array();
        if(input('?get.operation') && !empty(input('get.operation'))){
            $where['operation'] = input('get.operation/d');
        }else{
            $where = "1=1";
        }
        $administrative = $this->Operation->selectAdministrativeInfo($where);
        return $administrative;
    }

    /**
     * 解绑行政区域帐号
     */
    public function del(){
        $id=input('get.id/d');
        $res=$this->Operation->deleteData('administrative_user','a_id',$id,'帐号解绑');
        if($res){
            writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】删除成功：行政区域帐号',1,'operation_log');
            return json(array('code'=>1,'msg'=>'解绑成功'));
        }else{
            writelog(session($this->set['db_name'].'uid'),session($this->set['db_name'].'username'),'用户【'.session($this->set['db_name'].'username').'】删除失败：行政区域帐号',0,'operation_log');
            return json(array('code'=>0,'msg'=>'解绑失败'));
        }
    }

    /**
     * 检查区域是否已使用
     */
    public function checkArea(){
        $area_id=$this->request->get();
        $checkArea = $this->Operation->findArea($area_id);
        if ($checkArea){
            $json['code'] = 0;
            $json['msg'] = "负责区域已存在!";
            return json($json);
        }
    }
}